<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px">
    <el-form-item label="标题类型">
      <el-radio-group v-model="titleType">
        <el-radio label="#">#</el-radio>
        <el-radio label="##">##</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="token" prop="token">
      <el-input v-model="token"></el-input>
    </el-form-item>

    <el-form-item label="文档地址" prop="url">
      <el-input v-model="url"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">添加序号</el-button>
      <!-- <el-button @click="resetForm">重置</el-button> -->
    </el-form-item>
  </el-form>

  <el-input
    type="textarea"
    :autosize="{ minRows: 2, maxRows: 10 }"
    placeholder="复制转换后的内容到语雀文档中"
    v-model="result"
  >
  </el-input>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  getCurrentInstance,
  ref,
  toRefs,
} from "vue";
import axios from "axios";
import { MarkdownIndex } from "../utils/markdown-index";

export default defineComponent({
  setup() {
    const form = reactive({
      titleType: "#",
      token: "ob3wc5p+y/ElcQlfui4kuB7tr/t3cCTvBLgi6su5vIY=",
      url: "https://www.yuque.com/ccsens/tall/zpn8el",
    });

    const result = ref("");

    const rules = reactive({
      token: [
        {
          required: true,
          message: "请输入token",
        },
      ],
      url: [
        {
          required: true,
          message: "请输入语雀文档地址",
        },
      ],
    });

    const context = getCurrentInstance();

    /**
     * 更新文档
     */
    const updateDoc = async (path: string, token: string, data: string) => {
      try {
        const res = await axios.put(
          path,
          {
            body: data,
            _force_asl: 1,
          },
          {
            headers: { "X-Auth-Token": token },
          }
        );
      } catch (error) {
        throw new Error(error);
      }
    };

    // 获取文档数据
    const getDocInfo = async (path: string, token: string) => {
      try {
        const res = await axios.get(path, {
          headers: { "X-Auth-Token": token },
        });
        return res.data.data;
      } catch (error) {
        throw new Error(error);
      }
    };

    const onSubmit = () => {
      context.refs.form.validate(async (valid: boolean) => {
        if (valid) {
          try {
            const [login, book_slug, slug] = form.url
              .split("yuque.com/")[1]
              .split("/");
            const getDocPath = `/api/repos/${login}/${book_slug}/docs/${slug}?raw=1`;

            const docData = await getDocInfo(getDocPath, form.token); // 获取到的文档数据
            const markdownInstance = new MarkdownIndex(form.titleType);
            let lines = markdownInstance.addMarkdownIndex(
              docData.body.split("\n")
            );
            // console.log(
            //   "🚀 ~ file: markdown-form.vue ~ line 60 ~ getDocInfo ~ res",
            //   lines,
            //   lines.join("\n")
            // );
            console.log(lines.join("\n"));
            result.value = lines.join("\n");
            // 更新文档
            // https://www.yuque.com/yuque/developer/ogibph
            // 通过 API 创建的文档一旦在语雀上通过语雀的在线编辑器进行编辑，就会变成语雀的私有格式（富文本），之后通过 API 就只能读取文档内容，而不能更新文档了；
            // const updatePath = `/api/repos/${login}/${book_slug}/docs/${docData.id}`;
            // await updateDoc(updatePath, form.token, lines.join("\n"));
          } catch (error) {
            console.log(
              "🚀 ~ file: markdown-form.vue ~ line 125 ~ context.refs.form.validate ~ error",
              error
            );
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    // 重置
    // const resetForm = () => {
    //   context.refs.form.resetField();
    // };
    // , resetForm
    return { ...toRefs(form), result, rules, onSubmit };
  },
});
</script>
